#include "datatreehelper.h"
#include <QScriptEngine>
#include <QDebug>

QScriptValue dataTreeConstructor(QScriptContext *context, QScriptEngine *engine)
{
    QString tableName;
    QString fields;

    if(context->argumentCount() > 0)
        tableName = context->argument(0).toString();
    if(context->argumentCount() > 1)
        fields = context->argument(1).toString();

    DataTreeHelper* dtHelper = new DataTreeHelper(tableName, fields);
    dtHelper->setTableName(tableName);

    return engine->newQObject(dtHelper, QScriptEngine::ScriptOwnership);
}


DataTreeHelper::DataTreeHelper(const QString &tableName, const QString fields) :
    QObject(),
    m_tableName(tableName)
{
    if(fields.size()>0)
        m_fields = fields.split(';');
}

QStringList DataTreeHelper::tablesStringList()
{
    QStringList list;
    list.append(m_tableName);
    for(int i = 0; i < m_childs.size(); i++)
        m_childs.at(i)->tablesStringList(list);

    return list;
}

QStringList DataTreeHelper::tablesStringList( QStringList &list )
{
    list.append(m_tableName);
    for(int i = 0; i < m_childs.size(); i++)
        m_childs.at(i)->tablesStringList(list);

    return list;
}

QList<DataTreeHelper *> DataTreeHelper::dataTreeList()
{
    QList<DataTreeHelper *> list;
    list.append(this);
    for(int i = 0; i < m_childs.size(); i++)
        m_childs.at(i)->dataTreeList(list);

    return list;
}

QList<DataTreeHelper *> DataTreeHelper::dataTreeList(QList<DataTreeHelper *> &list)
{
    list.append(this);
    for(int i = 0; i < m_childs.size(); i++)
        m_childs.at(i)->dataTreeList(list);

    return list;
}

void DataTreeHelper::appendChild(DataTreeHelper *child)
{
    m_childs.append(child);
}

int DataTreeHelper::childsCount()
{
    return m_childs.count();
}

void DataTreeHelper::removeChild(int index)
{
    m_childs.removeAt(index);
}

void DataTreeHelper::debug()
{
    qDebug()<<m_tableName<<m_filter<<m_fields;
    qDebug()<<m_ids;
    for(int i = 0; i< m_childs.size(); i++) {
        qDebug()<<"childFor: "<<m_tableName;
        m_childs.at(i)->debug();
    }
}
